<template>
  <div class="order-page">
    <div class="page-header">
      <h2 class="page-title">我的订单</h2>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="房间名称">
          <el-input v-model="searchForm.roomName" placeholder="请输入房间名称查询" clearable></el-input>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select 
            v-model="searchForm.status" 
            placeholder="选择订单状态" 
            clearable
            @change="handleStatusChange"
            style="width:240px"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 订单列表 -->
    <div class="order-list" v-loading="loading">
      <el-card v-for="order in orderList" :key="order.id" class="order-card">
        <div class="card-header">
          <div class="room-info" @click="goToRoomDetail(order.roomId)">
            <el-image
              :src="order.roomImageUrl || ''"
              fit="cover"
              class="room-image"
            >
              <template #error>
                <div class="image-placeholder">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <div class="room-details">
              <h3 class="room-title">{{ order.roomName || '未知房间' }}</h3>
              <p class="room-price">￥{{ order.payNum || 0 }}</p>
            </div>
          </div>
          <div class="order-status">
            <el-tag :type="getStatusType(order.status)">
              {{ getStatusText(order.status) }}
            </el-tag>
          </div>
        </div>

        <div class="order-info">
          <div class="info-item">
            <el-icon><Ticket /></el-icon>
            <span>订单号：{{ order.id }}</span>
          </div>
          <div class="info-item">
            <el-icon><User /></el-icon>
            <span>入住人：{{ order.userName }}</span>
          </div>
          <div class="info-item">
            <el-icon><Phone /></el-icon>
            <span>客户联系电话：{{ order.userPhone }}</span>
          </div>
          <div class="info-item">
            <el-icon><Phone /></el-icon>
            <span>房东联系电话：{{ order.ownerPhone }}</span>
          </div>
          <div class="info-item">
            <el-icon><Calendar /></el-icon>
            <span>入住日期：{{ formatTime(order.inTime) }}</span>
          </div>
          <div class="info-item">
            <el-icon><Calendar /></el-icon>
            <span>退房日期：{{ formatTime(order.outTime) }}</span>
          </div>
          <div class="info-item">
            <el-icon><Timer /></el-icon>
            <span>创建时间：{{ formatTime(order.createTime) }}</span>
          </div>
          <div class="info-item">
            <el-icon><Timer /></el-icon>
            <span>订单金额：{{ order.payNum }}</span>
          </div>
        </div>

        <div class="card-actions">
          <el-button 
            v-if="order.status === '0'"
            type="primary" 
            size="small"
            @click="handlePay(order.id)"
          >
            立即支付
          </el-button>
          <el-button 
            v-if="order.status === '2'"
            type="success" 
            size="small"
            @click="confirmCheckIn(order.id)"
          >
            确认入住
          </el-button>

          <el-button 
            v-if="order.status === '0'"
            type="danger" 
            size="small"
            @click="handleCancel(order)"
          >
            取消订单
          </el-button>
          <el-button 
            size="small"
            @click="showDetail(order)"
          >
            订单详情
          </el-button>
        </div>
      </el-card>

      <!-- 空状态 -->
      <el-empty
        v-if="!orderList.length"
        description="暂无订单记录"
      />
    </div>

    <!-- 分页器 -->
    <div class="pagination-container" v-if="orderList.length">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 10, 20]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情弹窗 -->
    <el-dialog v-model="detailVisible" title="订单详情" width="500px">
      <div v-if="currentOrder" class="order-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="订单号">{{ currentOrder.id }}</el-descriptions-item>
          <el-descriptions-item label="房间名称">{{ currentOrder.roomName }}</el-descriptions-item>
          <el-descriptions-item label="入住人">{{ currentOrder.userName }}</el-descriptions-item>
          <el-descriptions-item label="客户联系电话">{{ currentOrder.userPhone }}</el-descriptions-item>
          <el-descriptions-item label="房东联系电话">{{ currentOrder.ownerPhone }}</el-descriptions-item>
          <el-descriptions-item label="入住日期">{{ formatTime(currentOrder.inTime) }}</el-descriptions-item>
          <el-descriptions-item label="退房日期">{{ formatTime(currentOrder.outTime) }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(currentOrder.status)">
              {{ getStatusText(currentOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ currentOrder.payNum || 0 }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatTime(currentOrder.createTime) }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="action-buttons">
          <el-button 
            v-if="currentOrder.status === 0"
            type="primary" 
            @click="handlePay(currentOrder)"
          >
            立即支付
          </el-button>

        </div>
      </div>
    </el-dialog>

    <!-- 取消订单对话框 -->
    <el-dialog
      v-model="cancelDialog.visible"
      title="取消订单"
      width="500px"
    >
      <div style="text-align: center; padding: 20px">
        确定要取消该订单吗？
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDialog.visible = false">取消</el-button>
          <el-button type="primary"
           @click="confirmCancel"
           :loading="cancelDialog.loading">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Ticket, User, Phone, Calendar, Timer, Picture } from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import request from '@/utils/request';

const router = useRouter();
const loading = ref(false);
const orderList = ref([]);
const currentPage = ref(1);
const pageSize = ref(3);
const total = ref(0);
const detailVisible = ref(false);
const currentOrder = ref(null);

// 搜索表单
const searchForm = reactive({
  roomName: '',
  status: ''
});

const statusOptions = ref([
  { label: '全部', value: '' },
  { label: '待支付', value: '0' },
  { label: '已支付', value: '1' },
  { label: '已确认', value: '2' },
  { label: '已入住', value: '3' },
  { label: '已取消', value: '4' }
]);

// 取消订单对话框数据
const cancelDialog = reactive({
  visible: false,
  loading: false,
  form: {
    id: null,
  }
});

// 取消表单校验规则
const cancelRules = {
  reason: [
    { required: true, message: '请输入取消原因', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ]
};

const cancelFormRef = ref(null);

// 获取订单列表
const getOrderList = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    };
    
    // 移除空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key];
      }
    });
    
    const res = await request.get('/orders/selectAll', { params });
    if (res.code === '200') {
      orderList.value = res.data.items || [];
      total.value = res.data.total || 0;
    } else {
      ElMessage.error(res.msg || '获取订单列表失败');
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
    ElMessage.error('获取订单列表失败');
  } finally {
    loading.value = false;
  }
};

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'warning',     // 待支付
    1: 'primary',  // 已支付
    2: 'success',  // 已确认
    3: 'info',  // 已入住
    4: 'danger'    // 已取消
  };
  return types[status] || 'info';
};

// 获取状态文本
const getStatusText = (status) => {
  const option = statusOptions.value.find(item => item.value === status);
  return option ? option.label : '未知状态';
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  return dayjs(time).format('YYYY-MM-DD HH:mm');
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  getOrderList();
};

// 重置表单
const resetForm = () => {
  searchForm.roomName = '';
  searchForm.status = '';
  currentPage.value = 1;
  getOrderList();
};

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  getOrderList();
};

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getOrderList();
};

// 显示订单详情
const showDetail = (order) => {
  currentOrder.value = order;
  detailVisible.value = true;
};

// 跳转到房间详情
const goToRoomDetail = (roomId) => {
  if (!roomId) {
    ElMessage.error('房间ID不存在');
    return;
  }
  console.log('Order 跳转到房间详情，roomId:', roomId, '类型:', typeof roomId);

  router.push({ 
    name: 'room_detail', 
    params: { roomId: roomId }
  });
};

// 支付订单
const handlePay = (orderId) => {
  ElMessageBox.confirm('确定要支付此订单吗？', '支付确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await request.put(`/orders/pay?orderId=${orderId}`);
      if (res.code === '200') {
        ElMessage.success('支付成功');
        getOrderList();
      } else {
        ElMessage.error(res.msg || '支付失败');
      }
    } catch (error) {
      console.error('支付失败:', error);
      ElMessage.error('支付失败');
    }
  }).catch(() => {});
};

// 确认入住
const confirmCheckIn = (orderId) => {
  ElMessageBox.confirm('确定要确认该订单入住吗？', '确认入住', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await request.put(`/orders/checkIn?orderId=${orderId}`);
      if (res.code === '200') {
        ElMessage.success('确认入住成功');
        getOrderList();
      } else {
        ElMessage.error(res.msg || '确认入住失败');
      }
    } catch (error) {
      console.error('确认入住失败:', error);
      ElMessage.error('确认入住失败');
    }
  }).catch(() => {});
};

// 显示取消订单对话框
const handleCancel = (order) => {
  cancelDialog.form.id = order.id;
  cancelDialog.visible = true;
};

// 确认取消订单
const confirmCancel = async () => {
  cancelDialog.loading = true;
  try {
    // 修改请求接口，移除原因参数
    const res = await request.put(`/orders/cancel?orderId=${cancelDialog.form.id}`);
    if (res.code === '200') {
      ElMessage.success('订单已取消');
      cancelDialog.visible = false;
      getOrderList();
    } else {
      ElMessage.error(res.msg || '取消订单失败');
    }
  } catch (error) {
    console.error('取消订单失败:', error);
    ElMessage.error('取消订单失败');
  } finally {
    cancelDialog.loading = false;
  }
};

// 处理状态变化
const handleStatusChange = (value) => {
  if (value === '') {
    searchForm.status = '';
  } else {
    const option = statusOptions.value.find(item => item.value === value);
    if (option) {
      searchForm.status = option.value;
    }
  }
  handleSearch();
};

onMounted(() => {
  getOrderList();
});
</script>

<style scoped>
.order-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.filter-container {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px;
}


.order-list {
  margin-bottom: 20px;
}

.order-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
}

.order-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.room-info {
  display: flex;
  align-items: center;
  gap: 15px;
  cursor: pointer;
}

.room-image {
  width: 120px;
  height: 80px;
  border-radius: 4px;
  object-fit: cover;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #909399;
}

.room-details {
  flex: 1;
}

.room-title {
  margin: 0 0 8px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.room-price {
  margin: 0;
  color: #f56c6c;
  font-weight: 600;
  font-size: 16px;
}

.order-info {
  padding: 15px 0;
  border-top: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
}

.info-item .el-icon {
  color: #909399;
}

.card-actions {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  flex-wrap: wrap;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.order-detail {
  padding: 10px;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 15px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .order-info {
    grid-template-columns: 1fr;
  }

  .room-info {
    flex-direction: column;
    align-items: flex-start;
  }

  .room-image {
    width: 100%;
    height: auto;
    aspect-ratio: 16/9;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .order-status {
    margin-top: 10px;
  }

  .card-actions {
    justify-content: center;
  }
}
</style>